<!-- 生产管理 基础数据 产品工段配置 productSectionConfig -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.productSectionConfig_add" @click="handleAdd">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete">删 除</el-button>
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导 入</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.productSectionConfig_edit" @click.stop="opendetailRow(scope.row)">编辑</el-button>
        <el-button icon="el-icon-document-copy" size="small" type="text" @click.stop="openCopyRow(scope.row)">复制</el-button>
        <el-button icon="el-icon-circle-close" v-if="scope.row.status == 1" size="small" type="text" @click.stop="handleDisable(scope.row)">禁用</el-button>
        <el-button icon="el-icon-circle-check" v-else size="small" type="text" @click.stop="handleEnable(scope.row)">启用</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click="$refs.crud.rowDel(scope.row)">删除</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <el-dialog custom-class="productSectionConfigDialog" ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" top="5vh" @close="closeDialog">
      <avue-form v-if="showDialog" ref="form" v-model="form" :option="formOption">
        <template #workSectionDataLabel="{}">
          <span>
            <el-tooltip class="item" effect="dark" content="设计工艺路线时，将会依据该处所选工段的顺序去排列工序的顺序" placement="top-start">
              <i class="el-icon-info"></i>
            </el-tooltip>
            工段
          </span>
        </template>
        <template #workSectionData>
          <el-button type="primary" size="small" style="margin-bottom: 10px" icon="el-icon-plus" @click="handleAddWorkSection">新 增</el-button>
          <el-table
            ref="workSectionRef"
            border
            v-tableDrag:[config]="workSection.data"
            row-key="id"
            height="300"
            :data="workSection.data"
            :row-class-name="tableRowClassName"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" align="center" width="60"> </el-table-column>
            <el-table-column prop="sectionName" label="工段名称">
              <template slot-scope="{ row, $index }">
                <!-- <span v-if="!row.id.includes('time-')">{{ row.sectionName }}</span> -->
                <el-cascader
                  size="mini"
                  popper-class="sectionCascaderPopper"
                  :options="workSectionData"
                  :show-all-levels="true"
                  :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"
                  v-model="row.sectionId"
                  :disabled="!row.id.includes('time-')"
                  :placeholder="`请选择 工段${$index + 1}`"
                  @change="(value) => handleWorkSectionChange(value, row, $index)"
                ></el-cascader>
              </template>
            </el-table-column>
            <el-table-column prop="sectionCode" label="工段编码"> </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button @click="handleWorkSectionRowDel(scope.row, scope.$index)" icon="el-icon-delete" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="submit"> <i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.importUrl"
      :formData="importConfig.formData"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      :configColumns="['dataRepeat']"
      @submit="codeClose"
    ></importDialogComp>
    <!-- 产品编码 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { getList, update, getAllSection, getDetail, enable, disable, remove } from '@/api/product/productSectionConfig';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters, mapState } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import tableDrag from '@/components/tableDrag.js';
import importDialogComp from '@/components/dialog/import/index.vue';
export default {
  name: 'ProductSectionConfig',
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    userTableConfig,
    importDialogComp
  },
  mixins: [userConfig()],
  directives: { tableDrag: tableDrag },
  data() {
    return {
      config: {
        elementSeletor: 'tbody',
        filter: '.filtered',
        onEnd: (event, oldValue, newValue) => {
          console.log('源数据', oldValue);
          console.log('改变后的数据', newValue);
        }
      },
      visibile: false,
      pageCode: 'PRODUCT_SECTION_CONFIG',
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        columnBtn: false,
        searchSpan: 6,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: true,
        menuWidth: 300,
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            order: 1,
            search: true
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            order: 2,
            search: true
          },
          {
            label: '产品型号',
            order: 3,
            prop: 'productPartModel'
          },
          {
            label: '产品工段',
            order: 4,
            prop: 'productSectionName',
            overHidden: true
          },
          {
            label: '备注',
            prop: 'remark',
            span: 24,
            order: 7,
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            maxlength: 300,
            showWordLimit: true,
            overHidden: true
          },
          {
            label: '创建人',
            width: 100,
            prop: 'creator',
            order: 5
          },
          {
            label: '创建时间',
            width: 140,
            prop: 'createTime',
            order: 6
          }
        ]
      },
      form: {},
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 90,
        detail: false,
        group: [
          {
            label: '产品信息',
            prop: 'partInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '产品编码',
                prop: 'productPartNo',
                type: 'search',
                disabled: true,
                placeholder: '请选择 产品编码',
                rules: [
                  {
                    required: true,
                    message: '请选择产品编码',
                    trigger: 'blur'
                  }
                ],
                appendClick: () => {
                  if (this.dialogTitle != '编辑') {
                    this.openUserCommonModal({ type: 'productPartNo' });
                  }
                }
              },
              {
                label: '产品名称',
                prop: 'productPartName',
                disabled: true,
                placeholder: '产品名称'
              },
              {
                label: '产品型号',
                prop: 'productPartModel',
                disabled: true,
                placeholder: '产品型号'
              }
            ]
          },
          {
            label: '产品工段',
            prop: 'partInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            display: true,
            column: [
              {
                label: '工段',
                prop: 'workSectionData',
                span: 24,
                formslot: true,
                rules: [
                  {
                    required: true,
                    trigger: 'blur',
                    validator: (rule, value, callback) => {
                      callback();
                    }
                  }
                ]
              },
              {
                label: '备注',
                prop: 'remark',
                type: 'textarea',
                span: 24,
                maxRows: 3,
                minRows: 3,
                maxlength: 300,
                showWordLimit: true
              }
            ]
          }
        ]
      },
      showDialog: false,
      dialogTitle: '新增',
      workSectionData: [],
      isAudit: false,
      importList: [],
      workSection: {
        data: [],
        option: {
          height: 300,
          calcHeight: 30,
          columnBtn: false,
          border: true,
          index: true,
          indexLabel: '序号',
          addBtn: false,
          viewBtn: false,
          editBtn: false,
          delBtn: true,
          selection: false,
          refreshBtn: false,
          sortable: true,
          dialogClickModal: false,
          menu: true,
          menuWidth: 180,
          column: [
            {
              label: '工段名称',
              prop: 'sectionName'
            },
            {
              label: '工段编码',
              prop: 'sectionCode'
            }
          ]
        },
        form: {},
        loading: false
      },
      importConfig: {
        show: false,
        importUrl: '/api/mes-product/part-master/section/import',
        exportName: '产品工段导入模版.xls',
        formData: {
          req: []
        },
        title: '产品工段导入'
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        editBtn: this.vaildData(this.permission.productSectionConfig_edit, false),
        addBtn: this.vaildData(this.permission.productSectionConfig_add, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.productPartId);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  activated() {
    this.getWorkSectionData();
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (!row.id.includes('time-')) {
        return 'filtered';
      }
      return '';
    },
    handleAdd() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.formOption.detail = false;
      this.formOption.group[1].display = true;
      this.$nextTick(() => {
        this.$refs.form.allDisabled = false;
      });
      this.workSection.data = [{ id: 'time-' + new Date().getTime(), sectionId: '', sectionCode: '', sectionName: '' }];
    },
    submit() {
      this.$refs.form.validate(async (valid, done) => {
        if (valid) {
          let workSectionData = this.workSection.data.filter((item) => item.sectionId);
          if (workSectionData.length === 0) {
            this.$message.error('请选择工段！');
            done();
            return;
          }
          let emptyWorkSectionData = this.workSection.data.filter((item) => !item.sectionId);
          if (emptyWorkSectionData && emptyWorkSectionData.length > 0) {
            this.$message.error('工段不能为空！');
            done();
            return;
          }
          // 检测是否有重复工段
          let isRepeatWorkSection = workSectionData.reduce((pre, cur) => {
            if (!pre.includes(cur.sectionId)) {
              pre.push(cur.sectionId);
            }
            return pre;
          }, []);
          if (isRepeatWorkSection.length < workSectionData.length) {
            this.$message.error('工段不能重复！');
            done();
            return;
          }
          this.workSection.data.forEach((item, index) => {
            item.sectionSequence = index + 1;
          });
          this.workSection.data.forEach((item) => {
            if (item.id.includes('time-')) {
              item.id = '';
            }
          });
          this.$set(this.form, 'workSectionList', this.workSection.data);
          delete this.form.workSectionData;
          delete this.form.createTime;
          delete this.form.createUserName;
          delete this.form.pageSections;
          console.log('this.form', this.form);
          update(this.form).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    opendetailRow(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.form = structuredClone(row);
      getDetail(row.productPartId).then((res) => {
        this.workSection.data = this._get(res, 'data.data', []);
      });
    },
    openCopyRow(row) {
      this.showDialog = true;
      this.dialogTitle = '新增';
      row.sections.forEach((item) => {
        item.id = 'time-' + item.id;
      });
      this.form.remark = row.remark;
      getDetail(row.productPartId).then((res) => {
        this.workSection.data = this._get(res, 'data.data', []);
      });
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.isLastest = true;

      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'productPartNo':
          this.modalName = 'partNoModal';
          this.$refs.commonModalTemplate.showModal();
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            url: '/api/mes-admin/part-master/page?semifinished=true',
            isPage: true,
            rowSelectionType: 'single',
            columnDefs: [
              // {
              //   label: '类型',
              //   prop: 'categoryId',
              //   type: 'tree',
              //   dicUrl: '/api/mes-admin/part-category/tree',
              //   props: {
              //     label: 'title',
              //     value: 'id'
              //   }
              // },
              {
                label: '产品编码',
                prop: 'partNo',
                search: true
              },
              {
                label: '产品名称',
                prop: 'name',
                search: true
              },
              {
                label: '产品型号',
                prop: 'partModel'
              },
              {
                label: '版本',
                prop: 'revision'
              },
              {
                label: '仓库物料类型',
                prop: 'partType',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                },
                dicUrl: '/api/blade-system/dict/dictionary?code=part_type'
              }
            ]
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partNoModal':
          this.form.productPartNo = this._get(rowData, 'partNo', '');
          this.form.productPartName = this._get(rowData, 'name', '');
          this.form.productPartId = this._get(rowData, 'id', '');
          this.form.productPartModel = this._get(rowData, 'partModel', '');
          break;

        default:
          break;
      }
    },
    getWorkSectionData() {
      getAllSection(1, 10000).then(
        (res) => {
          this.workSectionData = this._get(res, 'data.data.records', []);
        },
        (error) => {
          this.workSectionData = [];
        }
      );
    },
    handleWorkSectionChange(value, row, index) {
      let allWorkSections = this.workSectionData.reduce((pre, cur) => {
        if (cur.children) {
          cur.children.forEach((item) => {
            pre.push({
              sectionId: item.id,
              sectionName: item.name,
              sectionCode: item.code
            });
          });
        }
        pre.push({
          sectionId: cur.id,
          sectionName: cur.name,
          sectionCode: cur.code
        });
        return pre;
      }, []);
      let findSection = allWorkSections.find((item) => item.sectionId === value);
      if (findSection) {
        this.$set(this.workSection.data[index], 'sectionId', findSection.sectionId);
        this.$set(this.workSection.data[index], 'sectionName', findSection.sectionName);
        this.$set(this.workSection.data[index], 'sectionCode', findSection.sectionCode);
      }
    },
    handleAddWorkSection() {
      this.workSection.data.push({ id: 'time-' + new Date().getTime(), sectionId: '', sectionCode: '', sectionName: '' });
      this.$util.table.elTableScrollTorow(this.$refs.workSectionRef, this.workSection.data.length, 6);
    },
    handleWorkSectionRowDel(form, index) {
      this.deleteRow(index);
    },
    deleteRow(index) {
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.workSection.data.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {});
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.form = {};
    },
    handleImport() {
      this.importConfig.show = true;
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    handleEnable(row) {
      enable(row.productPartId).then((res) => {
        this.$message({
          type: 'success',
          message: res.data.msg
        });
        this.onLoad(this.page);
      });
    },
    handleDisable(row) {
      disable(row.productPartId).then((res) => {
        this.$message({
          type: 'success',
          message: res.data.msg
        });
        this.onLoad(this.page);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.productPartId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.titleLeft {
  display: flex;
  border-bottom: 1px solid #eeeeee;
  padding: 20px 0;
  .titleName {
    font-size: 16px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
  }
}
::v-deep .productSectionConfigDialog .el-dialog__body {
  max-height: 800px;
  overflow: auto;
  padding: 0 20px;
  .workSection-item {
    width: 50%;
    display: flex;
    margin-bottom: 8px;
  }
}
</style>
